﻿namespace Core.Implementation
{
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Diagnostics.Contracts;
	using Domain;
	using NHibernate;
	using NHibernate.Linq;
	using Providers.DataAccess;	

	internal class NHibernatePersonRepository : PersonRepository
	{

		public NHibernatePersonRepository(IDataAccessProvider dataAccessProvider)
		{
			CodeContract.Requires(dataAccessProvider != null);
			this.DataAccessProvider = dataAccessProvider;
		}

		public IDataAccessProvider DataAccessProvider
		{
			get; 
			private set;
		}

		private class PersonDataContext : NHibernateContext
		{
			public PersonDataContext(ISession session)
			: base(session)
			{
			}

			public IOrderedQueryable<Person> Persons
			{
				get
				{
					return Session.Linq<Person>();
				}
			}
		}

		private PersonDataContext CreateContext()
		{
			var sessionFactory = this.DataAccessProvider.CreateSessionFactory();

			return new PersonDataContext(sessionFactory.OpenSession());
		}
		
		public override Person Save(Person candidatePerson)
		{
			using (var context = CreateContext())
			{
				Person person = (Person)context.Session.SaveOrUpdateCopy(candidatePerson);

				//context.Session.Flush();

				return person;				
			}
		}
	}
}
